//
//  JWTCommons.m
//  JWT
//
//  Created by Apple on 2017/1/1.
//  Copyright © 2017年 com.jwtsoft. All rights reserved.
//

#import "JWTCommons.h"
//#import <objc/runtime.h>

#define DefaultThumImageHigth 90.0f
#define DefaultPressImageHigth 960.0f

@implementation JWTCommons
SHARED_INSTANCE_IMPLEMENTATION(JWTCommons)

/* get the fundation object from json string nsdata */
id NSJSONObjectWithData(NSData *nsdata)
{
    if(nsdata == nil)
        return nil;
    else
    {
        NSError *error;
        id obj = [NSJSONSerialization JSONObjectWithData:nsdata options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves|NSJSONReadingAllowFragments error:&error];
        if(error && !obj)
        {
            NSLog(@"nsdata json 解析错误:%@",error.description);
            return nil;
        }
        return obj;
    }
}

/* get the fundation object from json NSString */
id NSJSONObjectWithString(NSString *str)
{
    return NSJSONObjectWithData([str dataUsingEncoding:NSUTF8StringEncoding]);
}

/* get the json string data from the fundation object */
//#define NSJSONDataWithObject(dicObject)  [NSJSONSerialization dataWithJSONObject:dicObject options:NSJSONWritingPrettyPrinted error:nil]
id NSJSONDataWithObject(id dicObject)
{
    return [NSJSONSerialization dataWithJSONObject:dicObject options:NSJSONWritingPrettyPrinted error:nil];
}

/* get the json string data from the fundation object */
NSString* NSJSONStringWithObject(NSDictionary* dicObject)
{
    NSData *dateStr =  NSJSONDataWithObject(dicObject);
    return [[NSString alloc] initWithData:dateStr encoding:NSUTF8StringEncoding];
}

/**获取导航条的高度*/
float getNAVI_TOP_HEIGHT()
{
    return 64;
}
/**获取下面TabBar条的高度*/
float getTABBar_bottom_HEIGHT()
{
    return 44;
}

//将颜色转换成图片
+(UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size{
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return [self makeRoundedImage:image radius:0.0];
}
//将图片转换成圆角图片
+(UIImage *)makeRoundedImage:(UIImage *) image
                      radius: (float) radius;
{
    CALayer *imageLayer = [CALayer layer];
    imageLayer.frame = CGRectMake(0, 0, image.size.width, image.size.height);
    imageLayer.contents = (id) image.CGImage;
    
    imageLayer.masksToBounds = YES;
    imageLayer.cornerRadius = radius;
    
    UIGraphicsBeginImageContext(image.size);
    [imageLayer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *roundedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return roundedImage;
}

//校验手机号格式
-(NSInteger)validateMobile:(NSString *)mobile{
    
    /**
     * 手机号码
     * 移动：134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     * 联通：130,131,132,152,155,156,185,186
     * 电信：133,1349,153,180,189
     * @"^1(3[0-9]|5[0-35-9]|8[025-9])\\d{8}$";
     */
    
    NSInteger result; //返回结果
    /**
     10         *  中国移动：China Mobile
     11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     12         */
    NSString * CM = @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";
    /**
     15         *  中国联通：China Unicom
     16         * 130,131,132,152,155,156,185,186
     17         */
    NSString * CU = @"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    /**
     20         *  中国电信：China Telecom
     21         * 133,1349,153,180,189
     22         */
    NSString * CT = @"^1((33|53|8[019])[0-9]|349)\\d{7}$";
    
    NSPredicate *regextestCM = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    NSPredicate *regextestCU = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    NSPredicate *regextestCT = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    if ([regextestCM evaluateWithObject:mobile]) {
        result = 1; //中国移动
    }else if ([regextestCU evaluateWithObject:mobile]){
        result = 2; //中国联通
    }else if ([regextestCT evaluateWithObject:mobile]){
        result = 3; //中国电信
    }else{
        result = 0;  //手机号码格式不正确
    }
    
    return result;
    
}

/**
 字典转json
 */
- (NSString*)dictionaryToJson:(NSDictionary *)dic

{
    
    NSError *parseError = nil;
    
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
}

/**
 保存图片
 */
+(NSString*)saveToDocument:(UIImage*)image {
    UIImage* fixImage = [self fixOrientation:image];
    
    NSDateFormatter* formater = [[NSDateFormatter alloc] init];
    [formater setDateFormat:@"yyyyMMddHHmmssSSS"];
    NSString* fileName =[NSString stringWithFormat:@"%@.jpg", [formater stringFromDate:[NSDate date]]];
    
    NSString* filePath=[[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:fileName];
    
    //图片按0.5的质量压缩－》转换为NSData
    CGSize pressSize = CGSizeMake((DefaultPressImageHigth/fixImage.size.height) * fixImage.size.width, DefaultPressImageHigth);
    UIImage * pressImage = [self compressImage:fixImage withSize:pressSize];
    NSData *imageData = UIImageJPEGRepresentation(pressImage, 0.5);
    [imageData writeToFile:filePath atomically:YES];
    
    CGSize thumsize = CGSizeMake((DefaultThumImageHigth/fixImage.size.height) * fixImage.size.width, DefaultThumImageHigth);
    UIImage * thumImage = [self compressImage:fixImage withSize:thumsize];
    NSData * photo = UIImageJPEGRepresentation(thumImage, 0.5);
    NSString * thumfilePath = [NSString stringWithFormat:@"%@.jpg_thum", filePath];
    [photo writeToFile:thumfilePath atomically:YES];
    
    return filePath;
}

+ (UIImage *)compressImage:(UIImage *)image withSize:(CGSize)viewsize
{
    CGFloat imgHWScale = image.size.height/image.size.width;
    CGFloat viewHWScale = viewsize.height/viewsize.width;
    CGRect rect = CGRectZero;
    if (imgHWScale>viewHWScale)
    {
        rect.size.height = viewsize.width*imgHWScale;
        rect.size.width = viewsize.width;
        rect.origin.x = 0.0f;
        rect.origin.y =  (viewsize.height - rect.size.height)*0.5f;
    }
    else
    {
        CGFloat imgWHScale = image.size.width/image.size.height;
        rect.size.width = viewsize.height*imgWHScale;
        rect.size.height = viewsize.height;
        rect.origin.y = 0.0f;
        rect.origin.x = (viewsize.width - rect.size.width)*0.5f;
    }
    
    UIGraphicsBeginImageContext(viewsize);
    [image drawInRect:rect];
    UIImage *newimg = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return newimg;
}
+ (UIImage *)fixOrientation:(UIImage *)aImage {
    // No-op if the orientation is already correct
    if (aImage.imageOrientation == UIImageOrientationUp)
        return aImage;
    // We need to calculate the proper transformation to make the image upright.
    // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
    CGAffineTransform transform = CGAffineTransformIdentity;
    switch (aImage.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        default:
            break;
    }
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        default:
            break;
    }
    
    // Now we draw the underlying CGImage into a new context, applying the transform     // calculated above.
    CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,CGImageGetBitsPerComponent(aImage.CGImage), 0,CGImageGetColorSpace(aImage.CGImage),CGImageGetBitmapInfo(aImage.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (aImage.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);
            break;
        default:              CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);              break;
    }       // And now we just create a new UIImage from the drawing context
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}

/**判断对象是否为空*/
BOOL isEmpty(id obj)
{
    
    if(obj == nil)
    {
        return YES;
    }
    
    else if([obj isKindOfClass:[NSString class]])
    {
        NSString *objStr = (NSString *)obj;
        if ([objStr isEqual:@""] || [trimStringAllBlank(objStr) isEqual:@"0"])
        {
            return YES;
        }
        if(objStr.length == 0)
        {
            return YES;
        }
    }
    else if([obj isKindOfClass:[NSNumber class]])
    {
        NSNumber *objNum = (NSNumber *)obj;
        if([objNum intValue] == 0)
        {
            return YES;
        }
    }
    else if([obj isKindOfClass:[NSNull class]])
    {
        return YES;
    }
    else
    {
    }
    return NO;
}
/**去除所有的空格*/
NSString * trimStringAllBlank(NSString *oldString)
{
    NSString * newString = [oldString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    newString = [newString stringByReplacingOccurrencesOfString:@" " withString:@""];
    return newString;
}


@end
